type TPosition = [number, number];

import {
  MOUSEMAZE_POS_VAL
} from '../utils/constant';

const {
  // NOWAY,
  PASSD
} = MOUSEMAZE_POS_VAL;

export const findPathForMouseMaze = (maze: number[][], outseti?: TPosition, endi?: TPosition) => {
  const outset: TPosition = outseti ?? [0, 0];
  const end: TPosition = endi ?? [maze.length - 1, maze[maze.length - 1].length - 1];
  const faild: any = {};
  let currentPos: TPosition = outset;
  let path: TPosition[] = [outset];

  if (!maze[outset[0]]?.[outset[1]]) {
    return [];
  }

  while (currentPos && !(currentPos[0] === end[0] && currentPos[1] === end[1])) {
    const poss: TPosition[] = [
      [currentPos[0] - 1, currentPos[1]],
      [currentPos[0] + 1, currentPos[1]],
      [currentPos[0], currentPos[1] - 1],
      [currentPos[0], currentPos[1] + 1],
    ];

    for (let i = 0; i < poss.length; i++) {
      const pos = poss[i];
      const alreadyInPath = path.some(item => {
        return item[0] === pos[0] && item[1] === pos[1];
      });
      
      if (
        maze[pos[0]]?.[pos[1]] === PASSD
        && !alreadyInPath
        && !faild[JSON.stringify(pos)]
      ) {
        path.push(pos);
        currentPos = pos;
        break;
      } else if (i === (poss.length - 1)) {
        const key = JSON.stringify(path.pop());
        faild[key] = true;
        currentPos = path[path.length - 1];
      }
    }
  }
  
  return path;
};

// console.log(
//   findPathForMouseMaze([
//     [PASSD, NOWAY, NOWAY, NOWAY, NOWAY],
//     [PASSD, PASSD, PASSD, NOWAY, NOWAY],
//     [NOWAY, NOWAY, PASSD, NOWAY, NOWAY],
//     [NOWAY, NOWAY, PASSD, NOWAY, NOWAY],
//     [NOWAY, NOWAY, PASSD, PASSD, PASSD],
//   ], [0, 0], [4, 4])
// );
